<!--
 * @FilePath: Api_case.vue
 * @@author: wjj
 * @Date: 2025-08-06 10:01:15
 * @@Description: new js file
-->
<template>
  <!-- 全屏遮罩层 -->
  <div v-if="!selectEnvStatus" class="modal-mask">
    <!-- 居中卡片容器 -->

    <!-- 卡片内容，阻止点击事件冒泡到遮罩层 -->
    <div
      class="modal-card"
      @click.stop
      style="display: flex; justify-content: center; align-items: center"
    >
      <el-text class="modal-text" @click="closeModal">选择项目</el-text>
    </div>
  </div>

  <el-card
    style="height: 80px; border-radius: 50px"
    :class="{ folded: LayOutSettingStore.fold }"
    class="card_class"
  >
    <div style="display: flex; justify-content: space-between">
      <el-form :inline="true" class="form">
        <el-form-item>
          <el-input
            placeholder="请你输入模块用例名称"
            v-model="keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            :disabled="keyword ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button type="primary" size="default" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <div class="device-card" v-if="selectEnvStatus">
        已选项目：{{ EnvStore.envName }}
      </div>
    </div>
  </el-card>
  <el-card
    style="margin: 10px 0px; border-radius: 50px"
    :class="{ folded: LayOutSettingStore.fold }"
    class="card_class"
    v-if="selectEnvStatus"
  >
    <el-button
      type="primary"
      size="default"
      @click="addcaseModule"
      style="border-radius: 10px"
    >
      新增模块用例
    </el-button>
    <el-button
      type="primary"
      size="default"
      :disabled="selectIdArr.length ? false : true"
      @click="updateSelectcaseModule"
      style="border-radius: 10px"
    >
      批量执行
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      style="margin: 10px 0px"
      :data="allcaseModuleData"
      :row-class-name="tableRowClassName"
      height="500"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
        label="模块用例名称"
        align="center"
        prop="caseModuleName"
        show-overflow-tooltip
        class="case_table"
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.caseModuleName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
        class="case_table"
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.updateTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="执行次数"
        align="center"
        prop="startNumber"
        show-overflow-tooltip
        class="case_table"
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.startNumber }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="最新执行状态"
        align="center"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span style="min-height: 3px; min-width: 3px">
            {{ scope.row.status }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="步骤数"
        align="center"
        prop="stepNumber"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.stepNumber }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300px" align="center">
        <!-- eslint-disable -->
        <template #="{ row, $index }">
          <el-button type="primary" size="small" @click="startcaseModule(row)">
            <el-icon><Position /></el-icon>
            执行
          </el-button>
          <el-button type="primary" size="small" @click="editcaseModule(row)">
            <el-icon><CirclePlus /></el-icon>
            步骤
          </el-button>

          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="deletecaseModule(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50, 100, 200, 500]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHas"
      @size-change="handler"
    />
  </el-card>
</template>
   <script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, onMounted, onUnmounted, reactive, nextTick, markRaw } from 'vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import useSocketClient from '@/store/socket/socket_client'
import emmit from '@/utils/emitter'
import { useRoute, useRouter } from 'vue-router'
import {
  ElNotification,
  ElMessage,
  ElMessageBox,
  resultProps,
} from 'element-plus'
import request from '@/utils/request'
import {
  reqGetApiCaseModule,
  reqDeleteApiCaseModule,
} from '@/api/api_auto/api_case_module'
import type { UserResponseData, User } from '@/api/acl/user/type'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  CopyDocument,
} from '@element-plus/icons-vue'
import { reqGetOneApiPreject } from '@/api/api_auto/project'
import { da, el, ro } from 'element-plus/es/locale'
import { fallbackCopy, nimi_login } from '@/utils/common'
import apiEnvStore from '@/store/modules/api_env'
defineOptions({
  name: 'InterfaceAllCaseno',
})
//报告记录展示
const goto_allure = (row: any) => {
  router.push({
    name: 'InterfaceCaseReportDetail',
    query: { reportURL: row.report_URL },
  })
}
let reportShow = ref(false)
let reportShowTableData = ref([
  {
    id: 1,
    envName: 'nimi',
    caseModuleName: '登录',
    startTime: '2025-10-15',
    results_Total: 10,
    results_Passed: 10,
    results_Failed: '0 个',
    results_No_Tested: '0 个',
    results_Overall_Pass_Rate: '100.0%',
    api_Average_Time: '0.2s',
    api_Total_Time: '2s',
    report_URL: 'http://192.168.32.21:1780/nimi/pytest_report/20251014175618/',
  },
])
//初始化
// 控制模态框显示的状态

const router = useRouter()
const route = useRoute()
// 关闭模态框的方法
const closeModal = (goStatus = true) => {
  // 关闭后可以重新启用页面滚动（如果在显示时禁用了的话）

  if (goStatus) {
    router.push({
      name: 'InterfaceEnv',
    })
  }
}

// 处理遮罩层点击事件：可以设置为不允许点击遮罩关闭，或者添加确认逻辑
let selectEnvStatus = ref(true)
const resetEnv = async () => {
  let envId = localStorage.getItem('envId')
  if (envId) {
    let result = await reqGetOneApiPreject(parseInt(envId))
    if (result.code == 200) {
      EnvStore.envName = result.data.envProjectName
      EnvStore.envId = result.data.id
      EnvStore.BaseURL = result.data.BaseURL
      EnvStore.envVariable = JSON.parse(result.data.envVariable)
      EnvStore.envComponent = JSON.parse(result.data.envComponent)
    } else {
      ElMessage.error(result.msg)
    }
  }
  if (!EnvStore.envId) {
    selectEnvStatus.value = false
  }
  console.log(222)
  // localStorage.removeItem('envId')
}
onMounted(() => {
  // 可选：禁用背景页面滚动
  document.body.style.overflow = 'hidden'
  getHas()
  resetEnv()
})
onUnmounted(() => {
  document.body.style.overflow = 'auto'
})

//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(20)
//用户总个数
let total = ref<number>(0)
//存储全部用户的数组
let allcaseModuleData = ref<any>([])
//定义响应式数据控制抽屉的显示与隐藏

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (row.status == '失败') {
    return 'danger-row'
  }
  return ''
}

emmit.on('add_account11', (data: any) => {
  if (data.code == 200) {
    ElMessage.closeAll()
    ElMessage.success(data.msg)
  } else if (data.code == 201) {
    ElMessage.closeAll()
    ElMessage.success(data.msg)
    getHas()
  } else {
    ElMessage.error(data.msg)
  }
})

//准备一个数组存储批量更新的用户的ID
let selectIdArr = ref<User[]>([])
//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>('')
//获取模板setting仓库
let LayOutSettingStore = useLayOutSettingStore()

//组件挂载完毕操作
let EnvStore = apiEnvStore()

//获取全部已有的用户信息
const getHas = async (pager = 1, asc = 'desc') => {
  //收集当前页码
  pageNo.value = pager
  let result = await reqGetApiCaseModule(
    pageNo.value,
    pageSize.value,
    keyword.value,
    asc,
  )
  if (result.code == 200) {
    total.value = result.data.total
    allcaseModuleData.value = result.data.apiCaseModuleData
    // allcaseModuleData.value = [
    //   {
    //     id: 1,
    //     caseModuleName: '登录模块',
    //     updateTime: '2025-10-15',
    //     startNumber: 20,
    //     status: 'success',
    //     stepNumber: 20,
    //   },
    // ]
  }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHas()
}
const startcaseModule = (row: any) => {
  ElMessageBox.confirm(
    `确定执行【${row.caseModuleName}】模块用例吗?`,
    '模块用例执行',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      //自定义图标
      icon: markRaw(Star),
      //设置draggable属性为true来开启拖拽弹窗能力。 设置 overflow为 true 可以让拖拽范围超出可视区。
      draggable: true,
      overflow: true,
    },
  )
    .then(async () => {
      if (!row.id) {
        ElMessage.error('模块用例不存在')
        return
      }
      if (row.allCaseData.length == 0) {
        ElMessage.error('无用例可执行')
        return
      }
      // 使用 axios 发起 POST 请求
      request
        .post(
          '/auto_api/StartAPI',
          {
            caseModule_ids: [row.id],
            allCaseDatas: [row.allCaseData],
            env_name: EnvStore.envName,
            env_id: EnvStore.envId,
          },
          {
            headers: { 'Content-Type': 'application/json' },
          },
        )
        .then((response: any) => {
          if (response.code == 200) {
            ElMessage.success(response.msg)
            reset()
          } else {
            ElMessage.error(response.msg)
          }
        })
        .catch((error: any) => {
          ElMessage.error(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消执行模块用例',
      })
    })
}
//添加按钮的回调
const addcaseModule = () => {
  router.push({
    name: 'InterfaceCase',
  })
}
//编辑按钮的回调
const editcaseModule = (row: any) => {
  EnvStore.case_module_id = row.id
  router.push({
    name: 'InterfaceCase',
    query: { caseModuleId: row.id },
  })
}
//编辑按钮的回调
const deletecaseModule = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个模块吗？', '提示', {
      type: 'warning',
    })
    let result = await reqDeleteApiCaseModule(row.id)
    if (result.code == 200) {
      ElMessage.success(result.msg)
      getHas()
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    // 用户取消删除
  }
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value
}

//批量更新按钮的回调
const updateSelectcaseModule = async () => {
  // TODO ElMessageBox使用
  ElMessageBox.confirm(
    '确定批量执行模块用例吗? 执行前请检查用例顺序是否正确?',
    '批量执行',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      //自定义图标
      icon: markRaw(Star),
      //设置draggable属性为true来开启拖拽弹窗能力。 设置 overflow为 true 可以让拖拽范围超出可视区。
      draggable: true,
      overflow: true,
    },
  )
    .then(async () => {
      //整理批量更新的参数
      let caseList: any = selectIdArr.value.map((item: any) => {
        console.log(item)
        return item.allCaseData
      })
      let idList: any = selectIdArr.value.map((item: any) => {
        console.log(item)
        return item.id
      })
      console.log(caseList)
      // 使用 axios 发起 POST 请求
      request
        .post(
          '/auto_api/StartAPI',
          {
            caseModule_ids: idList,
            allCaseDatas: caseList,
            env_name: EnvStore.envName,
            env_id: EnvStore.envId,
          },
          {
            headers: { 'Content-Type': 'application/json' },
          },
        )
        .then((response: any) => {
          if (response.code == 200) {
            ElMessage.success(response.msg)
            reset()
          } else {
            ElMessage.error(response.msg)
          }
        })
        .catch((error: any) => {
          ElMessage.error(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消批量更新操作',
      })
    })
}

//搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHas()
  //清空关键字
  // keyword.value = ''
}
//重置按钮
const reset = () => {
  LayOutSettingStore.refsh = !LayOutSettingStore.refsh
}
</script>
    <script lang="ts">
export default {
  name: 'user',
}
</script>
<style scoped lang="scss">
/* 遮罩层样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent; /* 关键：背景完全透明 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  pointer-events: none; /* 关键：允许所有点击事件穿透此容器[1,3](@ref) */
}

/* 卡片包装容器，用于居中 */
.modal-text {
  font: 5em sans-serif;
  color: transparent;
  -webkit-text-stroke: 1.2px rgba(255, 64, 70, 0.9);
  letter-spacing: 1.5px;
  text-shadow: 0 0 8px rgba(255, 64, 70, 0.4), 0 0 15px rgba(64, 158, 255, 0.2);
  text-transform: uppercase;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  padding: 5px 12px;

  border-radius: 4px;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
/* 卡片本体样式 */
.modal-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  animation: modalAppear 0.3s ease-out;
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  width: 500px;
  height: 200px;

  pointer-events: auto;
}

/* 卡片出现动画 */
@keyframes modalAppear {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-card {
    width: 95%;
    margin: 10px;
  }

  .card-header,
  .card-body,
  .card-footer {
    padding-left: 20px;
    padding-right: 20px;
  }
}
.card_class {
  max-width: max(1250px, calc(100vw - 250px));
}
.card_class.folded {
  max-width: max(1250px, calc(100vw - 100px)); /* 折叠状态 */
}
.device-card {
  background: rgba(35, 29, 204, 0.2);
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 50px;
  max-width: 280px;
  margin-right: 30px;
  margin-bottom: 15px;
}
:deep(.danger-row) {
  --el-table-tr-bg-color: rgba(220, 125, 177, 0.5);
}
.case_table {
  min-width: 60px;
}

.form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
    